package org.example.springoauth2.securitycommon.util;

import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;
import org.example.springoauth2.securitycommon.entity.SysUser;
import org.springframework.security.authentication.AuthenticationServiceException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hzq
 * @date 2021/9/13 10:59
 */
@UtilityClass
public class SecurityUtil {

    public String obtainCode(HttpServletRequest request) {
        String code = request.getParameter("code");
        if (StrUtil.isBlank(code))
            throw new AuthenticationServiceException("请求参数没有code");
        return code;
    }

    public String obtainAppId(HttpServletRequest request) {
        String appId = request.getParameter("appId");
        if (StrUtil.isBlank(appId))
            throw new AuthenticationServiceException("请求参数没有 appId");
        return appId;
    }

    public String obtainPhone(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        if (StrUtil.isBlank(phone))
            throw new AuthenticationServiceException("请求参数没有 phone");
        return phone;
    }

    public String obtainOpenidByPrincipal(Object principal) {
        if (principal instanceof SysUser) {
            return ((SysUser) principal).getJdbcUser().getJdbcUserAuth().getKey();
        } else if (principal instanceof String) {
            return (String) principal;
        }
        return null;
    }
}
